package com.cxh.rmsq.ui.fragment.self

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.Constant
import com.cxh.rmsq.db.model.MineBean
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource2
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.net.newNet.VipViewModel
import com.cxh.rmsq.ui.activity.WebViewActivity
import com.cxh.rmsq.ui.adapter.self.PrivilegeListAdapter
import com.cxh.rmsq.ui.adapter.self.VipProductListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.dialog.PayPopup
import com.cxh.rmsq.utils.dialog.PayQrcodePopup
import com.cxh.rmsq.utils.loadImage
import com.cxh.rmsq.utils.wechatPay
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import com.cxh.rmsq.wx.AuthResult
import com.cxh.rmsq.wx.PayResult
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xuexiang.xui.widget.imageview.RadiusImageView

private const val VIP = "vip"
private const val NICK_NAME = "nick_name"
private const val AVATOR = "avator"

class VIPFragment : BaseFragment() {
    private var param1: Int? = 0

    private lateinit var refreshList: SmartRefreshLayout
    private lateinit var tvConfirm: TextView
    private lateinit var tv_vip_text: TextView
    private lateinit var tv_time: TextView
    private lateinit var tv_nickName: TextView
    private lateinit var tv_service: TextView
    private lateinit var rv_pro_list: RecyclerView
    private lateinit var rv_privilege_list: RecyclerView
    private lateinit var iv_is_yes: ImageView
    private lateinit var iv_bac_top: ImageView
    private lateinit var riv_header: RadiusImageView
    private lateinit var checkbox1: CheckBox

    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(VipViewModel::class.java)
    }
    private val viewPayModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }

    var proId = 0
    var money = 0.0
    var name = ""
    private var userInfoViewModel: UserInfoViewModel? = null

    private val SDK_PAY_FLAG = 1
    private val SDK_AUTH_FLAG = 2

    override fun getLayoutResId(): Int {
        return R.layout.fragment_v_i_p
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {

    }

    companion object {
        fun newInstance(param1: Int/*, name: String, avator: String*/): VIPFragment {
            val fragment = VIPFragment()
            val args = Bundle()
            args.putInt(VIP, param1)
//            args.putString(NICK_NAME, name)
//            args.putString(AVATOR, avator)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<RelativeLayout>(R.id.cl_toolbar).setPadding(0, 0, 0, 0)
        BarUtils.setStatusBarColor(requireActivity(), ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(requireActivity(), true)

        param1 = requireArguments().getInt(VIP)
        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)

        riv_header = view.findViewById(R.id.riv_header) as RadiusImageView
        rv_pro_list = view.findViewById(R.id.rv_pro_list) as RecyclerView
        rv_privilege_list = view.findViewById(R.id.rv_privilege_list) as RecyclerView
        tvConfirm = view.findViewById(R.id.tv_confirm)
        iv_is_yes = view.findViewById(R.id.iv_is_yes)
        tv_time = view.findViewById(R.id.tv_time)
        tv_nickName = view.findViewById(R.id.tv_nickName)
        tv_vip_text = view.findViewById(R.id.tv_vip_text)
        tv_service = view.findViewById(R.id.tv_service)
        checkbox1 = view.findViewById(R.id.checkbox1)
        iv_bac_top = view.findViewById(R.id.iv_bac_top)
        refreshList = view.findViewById(R.id.refresh_list) as SmartRefreshLayout

        refreshList.resetNoMoreData()
        refreshList.setEnableLoadMore(false)
        refreshList.setEnableRefresh(true)
        refreshList.setRefreshHeader(MaterialHeader(activity))
        refreshList.setRefreshFooter(ClassicsFooter(activity))
        refreshList.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {

            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
               onResume()
            }
        })

        initRegistrationTerms()

//        tv_nickName.text = requireArguments().getString(NICK_NAME)

        tvConfirm.setOnClickListener {
            if (!checkbox1.isChecked) {
                showToast("请阅读并同意人脉社区《会员服务协议》")
                return@setOnClickListener
            }
            popPay(proId, money.toString())
        }
    }

    override fun onResume() {
        super.onResume()
        userInfoViewModel!!.requestUserSelfInfo(IMManager.getInstance().currentId)
        userInfoViewModel!!.userSelfInfo.observe(this) { resource: Resource2<MineBean?> ->
            if (resource.status == Status.SUCCESS && resource.data != null) {
                val info = resource.data
                name = info.nickname.toString()
                loadImage(info.avatar!!, riv_header)
                SPUtils.getInstance().put("vipLevel", info.vipLevel)

                viewModel.getProductInfo(1) {//1.普通vip 2.谁喜欢我 3.SVIP
                    if (refreshList.isRefreshing) {
                        refreshList.finishRefresh()
                    }
                    if (it.code == 200) {
                        tv_vip_text.text = "尊享" + it.data.vipPrivilegesNumber + "项特权"
                        if (it.data.isOpenVip) {//是否是会员
                            tv_nickName.text = name
                            tv_time.text = "VIP会员" + TimeUtils.millis2String(
                                it.data.vipExpirationTime,
                                "yyyy-MM-dd"
                            ) + "到期，购买后延长有效期"
                            tv_time.isVisible = true
                            iv_bac_top.setImageResource(R.mipmap.bac_openivp_yes)
                            iv_is_yes.setImageResource(R.mipmap.icon_openvip_yes)
                        } else {
                            tv_nickName.text = "暂未开通"
                            tv_time.isVisible = false
                            iv_bac_top.setImageResource(R.mipmap.bac_openivp_no)
                            iv_is_yes.setImageResource(R.mipmap.icon_openvip_no)
                        }
                        if (it.data.findProductInfo!!.size > 0) {
                            rv_pro_list.setLayoutManager(GridLayoutManager(activity, 3))
                            var productListAdapter = VipProductListAdapter()
                            rv_pro_list.setAdapter(productListAdapter)
                            productListAdapter.setNewInstance(it.data.findProductInfo)
                            proId = productListAdapter.data[it.data.findProductInfo!!.size - 1].id
                            money = productListAdapter.data[it.data.findProductInfo!!.size - 1].actualPrice

                            productListAdapter.setSelectPos(it.data.findProductInfo!!.size - 1)
                            productListAdapter.setOnItemClickListener { adapter, view, position ->
                                if (position != productListAdapter.getSelectPos()) {
                                    productListAdapter.setSelectPos(position)
                                    productListAdapter.notifyDataSetChanged()
                                    proId = productListAdapter.data[position].id
                                    money = productListAdapter.data[position].actualPrice
                                }
                            }
                        }
                        if (it.data.vipPrivileges!!.size > 0) {
                            rv_privilege_list.setLayoutManager(LinearLayoutManager(activity))
                            var listAdapter = PrivilegeListAdapter(1)
//                    listAdapter.setEmptyView(View.inflate(requireActivity(), R.layout.empty_data_layout, null))
                            rv_privilege_list.setAdapter(listAdapter)
                            listAdapter.setNewInstance(it.data.vipPrivileges)

                        }
                    }
                }
            }
        }

    }

    private fun popPay(id: Int, money: String) {
        XPopup.Builder(activity)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(PayPopup(requireContext(), money,"vip", object : PayPopup.onClick {
                override fun click(content: String, s1: Int) {
                    val paramsMap = HashMap<String, Any>()
                    paramsMap["productId"] = id
                    paramsMap["payWay"] = s1 //1：微信支付 2：支付宝 3：apple支付  4 二维码付款  5 支付宝二维码付款
                    paramsMap["type"] = 2 //1 藏宝 2 会员
                    viewPayModel.createOrder(paramsMap) {
                        if (it.code == 200) {
                            SPUtils.getInstance().put("orderId", it.data.id.toString())
                            when (s1) {
                                1 -> {
                                    val wxapi = WXAPIFactory.createWXAPI(
                                        requireActivity(),
                                        Constant.WECHAT_APP_ID,
                                        true
                                    )

                                    // 将该app注册到微信
                                    wxapi.registerApp(Constant.WECHAT_APP_ID)
                                    if (!wxapi.isWXAppInstalled) {
                                        Log.e("===", "你没有安装微信")
                                        ToastUtils.showToast("你没有安装微信")
                                        return@createOrder
                                    }
                                    wechatPay(wxapi, it.data.wxPayOrderResult!!)
                                }

                                2 ->{
                                    val payRunnable = Runnable {
                                        val alipay = PayTask(requireActivity())
                                        val result = alipay.payV2(it.data.alipayResponse, true)
                                        Log.i("msp", result.toString())
                                        val msg = Message()
                                        msg.what = SDK_PAY_FLAG
                                        msg.obj = result
                                        mHandler.sendMessage(msg)
                                    }

                                    // 必须异步调用
                                    val payThread = Thread(payRunnable)
                                    payThread.start()
                                }

                                4, 5 -> {
                                    XPopup.Builder(activity)
                                        .dismissOnTouchOutside(false)
                                        .dismissOnBackPressed(false)
                                        .asCustom(PayQrcodePopup(requireContext(), s1,  it.data.codeUrl.toString(), object : PayQrcodePopup.onClick {
                                            override fun click(content: String, s1: Int) {
                                                onResume()
                                            }
                                        })).show()
                                }

                            }


                        } else {
                            ToastUtils.showToast(it.msg)
                        }
                    }
                }
            })).show()
    }

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        @Suppress("unused")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showToast("购买成功")
                        onResume()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showToast("购买失败")
                    }
                }

                SDK_AUTH_FLAG -> {
                    val authResult = AuthResult(msg.obj as Map<String?, String?>, true)
                    val resultStatus: String = authResult.getResultStatus()

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(
                            resultStatus,
                            "9000"
                        ) && TextUtils.equals(authResult.getResultCode(), "200")
                    ) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtils.showToast("授权成功")
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtils.showToast("授权失败")
                    }
                }

                else -> {}
            }
        }
    }
    private fun initRegistrationTerms() {
        //协议文字及点击事件设置
        val serviceStr = tv_service.text.toString().trim { it <= ' ' }
        val stringBuilder = SpannableStringBuilder(serviceStr)
        val clickableSpanOne: ClickableSpan = object : ClickableSpan() {
            override fun onClick(view: View) {
                val intent = Intent(
                    requireActivity(),
                    WebViewActivity::class.java
                )
                intent.putExtra(WebViewActivity.PARAMS_TITLE, "会员服务")
                intent.putExtra(WebViewActivity.PARAMS_URL, Constant.vipAgreement)
                startActivity(intent)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#333333")
                // 设置下划线 true显示、false不显示
                //paint.setTypeface(Typeface.DEFAULT_BOLD);
                ds.isUnderlineText = false
            }
        }

        stringBuilder.setSpan(
            clickableSpanOne,
            9,
            tv_service.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        // 不设置点击不生效
        tv_service.text = stringBuilder
        tv_service.movementMethod = LinkMovementMethod.getInstance() // 不设置 没有点击事件
        tv_service.highlightColor = Color.TRANSPARENT // 设置点击后的颜色为透明
    }
}